package com.example.demo.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：IPv4地址和int数字的互换
 *
 * @author zhanglei
 * @date 2024/01/16 2:19 PM
 */
public class IpKit {

	private final static String PATTERN_STR = "\\d+";
	private final static Integer LEN_4 = 4;

	/**
	 * IPv4地址转换为int类型数字
	 *
	 * @param ipv4Addr
	 * @return
	 */
	public static int ipToInt(String ipv4Addr) {
		// 判断是否是ip格式的
		if (!isIpv4Address(ipv4Addr)) {
			throw new RuntimeException("无效的IP");
		}

		// 匹配数字
		Pattern pattern = Pattern.compile(PATTERN_STR);
		Matcher matcher = pattern.matcher(ipv4Addr);
		int result = 0;
		int counter = 0;
		while (matcher.find()) {
			int value = Integer.parseInt(matcher.group());
			result = (value << 8 * (3 - counter++)) | result;
		}
		return result;
	}

	/**
	 * 判断是否为ipv4地址
	 *
	 * @param ipv4Addr
	 * @return
	 */
	private static boolean isIpv4Address(String ipv4Addr) {
		// 0-255的数字
		String lower = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])";
		String regex = lower + "(\\." + lower + "){3}";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(ipv4Addr);
		return matcher.matches();
	}

	/**
	 * 将int数字转换成ipv4地址
	 *
	 * @param ip
	 * @return
	 */
	public static String intToIp(int ip) {
		StringBuilder sb = new StringBuilder();
		int num;
		// 是否需要加入'.'
		boolean needPoint = false;
		for (int i = 0; i < LEN_4; i++) {
			if (needPoint) {
				sb.append('.');
			}
			needPoint = true;
			int offset = 8 * (3 - i);
			num = (ip >> offset) & 0xff;
			sb.append(num);
		}
		return sb.toString();
	}

}